import api from './api.js'
Vue.component('Products', {
  template: `
    <ul>
      <li v-for="product in products" :key="product.id">
        {{product.title}}: ￥{{product.price}}
        <button @click="addToCart(product)" :disabled="product.inventory <= 0">放入购物车</button>
      </li>
    </ul>
  `,

  data() {
    return {
      products: [],
      cartItems: []
    }
  },

  methods: {
    addToCart(product) {
      const result = this.cartItems.find(item => item.id === product.id)
      if (result) {
        result.quantity++
      } else {
        const cartItem = {
          ...product,
          quantity: 1
        }
        this.cartItems.push(cartItem)
      }

      product.inventory--
      
      this.$emit('add-to-cart', this.cartItems)
    }
  },

  async mounted() {
    const products = await api.getProducts()
    this.products = products
  },
})